import os
import pygame

def load_music(name):
    	class NoneMusic:
	    	def play(self): pass
	if not pygame.mixer or pygame.mixer.init():
		return NoneMusic
	fullname = os.path.join('gfx', name)
	try:
	    	music = pygame.mixer.music.load(fullname)
	except pygame.error, message:
	    print 'Cannot load music:', fullname
	    raise SystemExit, message
	pygame.mixer.music.set_volumn = 0.3
	return music

def load_sound(name):
    class NoneSound:
        def play(self): pass
    if not pygame.mixer or not pygame.mixer.get_init():
        return NoneSound()
    fullname = os.path.join('gfx', name)
    try:
        sound = pygame.mixer.Sound(fullname)
    except pygame.error, message:
        print 'Cannot load sound:', fullname
        raise SystemExit, message
    return sound

def li(file):
	try: image = pygame.image.load(os.path.join('gfx', file))
	except pygame.error, message: print 'Cannot load image:', file; raise SystemExit, message
	image = image.convert_alpha()
	image.set_alpha(255, pygame.RLEACCEL)
	return image

def myDir(o):
	return dict([(x, getattr(o, x)) for x in dir(o)]) 

def parseUserAction(acts):
   	myact = acts.split(" ")
    	if len(myact) != 2:
		return None
	if myact[0][0] != '/':
	    	return None
	action = myact[0][1].lower()
	result = {'n': 'rename',}
	if action in result.keys(): 
		return result[action]
	return None


class Resource:
    def __init__(self, name, tilesize):
        
        self.res=self.load_image(name)
        _, _, w, h=self.res.get_rect()
        self.tiles=[]
        for y in range(0, h/tilesize):
            for x in range(0, w/tilesize):
                tile = pygame.Surface((tilesize, tilesize), depth=self.res)
                chop_rect=(x*tilesize, y*tilesize, tilesize, tilesize)
                tile.blit(self.res, (0, 0), chop_rect)
                self.tiles.append(tile)
                
    def get(self, no):
        return self.tiles[no]
    
    def load_image(self, name):
        try:
            image = pygame.image.load(name)
        except pygame.error, message:
            print 'Cannot load imageCursor:', name
            raise SystemExit, message

        image = image.convert_alpha()
        image.set_alpha(255, pygame.RLEACCEL)
        return image


def load_image(file, transparent = 1):
	"loads an image, prepares it for play"
	#file = os.path.join('data', file)
	try:
	    surface = pygame.image.load(file)
	except pygame.error:
	    raise SystemExit, 'Could not load image "%s" %s'%(file, pygame.get_error())
	if transparent:
	    corner = surface.get_at((0, 0))
	    surface.set_colorkey(corner, pygame.RLEACCEL)
	return surface.convert()

def load_images(trans, *files):
	imgs = []
	for file in files:
	    imgs.append(load_image(file, trans))
	return imgs

def load_sheet(sheet, pos, size, transparent = 1):
	image = pygame.Surface(size)
	image.blit(sheet, pos)
	if transparent:
	    corner = image.get_at((0, 0))
	    image.set_colorkey(corner, pygame.RLEACCEL)
	return image.convert()

def load_sheet2(sheet, pos, area, size, transparent = 1):
    image = pygame.Surface(size)
    image.blit(sheet, pos, area)
    if transparent:
	corner = image.get_at((0, 0))
	image.set_colorkey(corner, pygame.RLEACCEL)
    return image.convert()


def wrapText(text, font, width):
    lineWidth = font.size(text)[0]
    if lineWidth > width:
        words = text.split(' ')
        i = 1
        while i < len(words):
            currLine = ' '.join(words[:-i]) 
            if font.size(currLine)[0] <= width:
                return currLine + "\n" + wrapText(' '.join(words[len(words)-i:]),font,width)
            i += 1
    else:
        return text

def renderText(text, font, antialias, color, size, autosize, wordwrap):
    lines = text.split('\n')
    
    #Wordwrapping
    if wordwrap and not autosize:
        for i in xrange(len(lines)):
            line = lines[i]
            del lines[i]
            lines[i:i] = wrapText(line, font, size[0]).split('\n')
    
    #Text Rendering       
    if len(lines) == 1:
        #Single line text
        return font.render(text, antialias, color)
        
    else:
        #Multi line text
        lineHeight = font.get_linesize()
        
        height = lineHeight * len(lines)
        
        width = 0
        lineSurfs = []
        
        for line in lines:
            linesurf = font.render(line, antialias, color)
            lineSurfs.append(linesurf) 
            if linesurf.get_width() > width:
                width = linesurf.get_width()
        
        surf = pygame.Surface((width,height), pygame.SRCALPHA)
        
        for i in xrange(len(lineSurfs)):
            surf.blit(lineSurfs[i], (0,i * lineHeight))
    
        return surf

